//
// Created by ssii on 2020/3/11.
//

#include <signal.h>
#include <iostream>
#include <Thread/WorkThreadPool.h>
#include "Util/logger.h"
#include "Network/TcpClient.h"

using namespace std;
using namespace toolkit;


class TestClient : public TcpClient {

public:
    typedef std::shared_ptr<TestClient> Ptr;

    TestClient(string &&severport) : _serverPort(severport), TcpClient() {
        DebugL;
    }

    ~TestClient() {
        DebugL;
    }

    bool boot = false;


protected:
    virtual void onConnect(const SockException &ex) override {
//        boot = true;
        //连接结果事件
        InfoL << (ex ? ex.what() : "success");
    }

    virtual void onRecv(const Buffer::Ptr &pBuf) override {
        boot = true;
        //接收数据事件
        _sTick = stol(pBuf->data(), 0, 10);
        DebugL << pBuf->data() << " from port:" << get_peer_port();
    }

    virtual void onFlush() override {
        //发送阻塞后，缓存清空事件
        DebugL;
    }

    virtual void onErr(const SockException &ex) override {
        boot = false;
        //断开连接事件，一般是EOF
        WarnL << ex.what();
    }

    virtual void onManager() override {
        //定时发送数据到服务器
        BufferRaw::Ptr buf = obtainBuffer();
        if (buf) {
//            buf->assign();

            (*this) << _serverPort <<":"<< ++_sTick<< (Buffer::Ptr &) buf;
//            _nTick = _sTick;
        }
    }

private:
    string _serverPort = "10000";
    long _sTick = 0;

};


int main() {
    // 设置日志系统
    Logger::Instance().add(std::make_shared<ConsoleChannel>());
    Logger::Instance().setWriter(std::make_shared<AsyncLogWriter>());

    TestClient *pClient = new TestClient("10000");
    TestClient::Ptr client(pClient);//必须使用智能指针


    WorkThreadPool::Instance().getPoller()->doDelayTask(3000, [client]() {
        if (!client->boot)
            client->startConnect("127.0.0.1", 1125);//连接服务器
        sleep(10);
        return 1;
    });
    //退出程序事件处理
    static semaphore sem;
    signal(SIGINT, [](int) { sem.post(); });// 设置退出信号
    sem.wait();
    return 0;
}